package com.jilijili.controller;

import com.jilijili.grace.result.GraceJSONResult;
import com.jilijili.grace.result.ResponseStatusEnum;
import com.jilijili.pojo.Users;
import com.jilijili.pojo.bo.RegisterLoginBo;
import com.jilijili.pojo.vo.UsersVo;
import com.jilijili.service.UsersService;
import com.jilijili.utils.IPUtil;
import com.jilijili.utils.redis.RedisOperator;
import com.jilijili.utils.tencent.SMSUtils;
import io.swagger.annotations.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.UUID;

@Slf4j
@Api(value = "通信控制器", tags = "通信接口模块", produces = "ljj", consumes = "app")
@RestController
@RequestMapping("/api/passport")
public class PassportController extends BaseInfoProperties {

    @Resource
    private SMSUtils smsUtils;

    @Resource
    private RedisOperator redis;

    @Resource
    private UsersService usersService;


    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "用户id", required = true),
    })
    @ApiOperation(value = "用户登出")
    @PostMapping("/logout")
    public GraceJSONResult login(@Valid @RequestParam("userId") String userId,
                                 HttpServletRequest request) {
        // 清除会话信息,清除本地用户信息和token信息
        redis.del(REDIS_USER_TOKEN + ":" + userId);
        return GraceJSONResult.ok();
    }


    @ApiImplicitParams({
            @ApiImplicitParam(name = "mobile", value = "手机号", required = true),
            @ApiImplicitParam(name = "String", value = "验证码", required = true)
    })
    @ApiOperation(value = "登录或者注册")
    @PostMapping("/login")
    public GraceJSONResult login(@Valid @RequestBody() RegisterLoginBo registerLoginBo,
                                 HttpServletRequest request) {
        // 判断BindingResult中是否保存了错误的验证信息,如果有,测需要返回到前段
        // if( result.hashErrors())
        //  map<String,String> map = getErrors(result);
        //  return GraceJsonResult.errorMap(map);

        // [1] 判断Redis中的 验证码是否过期,或者验证码过时不一致
        String smsCode = registerLoginBo.getSmsCode();
        String mobile = registerLoginBo.getMobile();
        String redisCode = this.redis.get(MOBILE_SMSCODE + ":" + mobile);

        // [2] 验证码过时 或者 验证码不一致 返回错误信息
        if (StringUtils.isBlank(redisCode) || !redisCode.equalsIgnoreCase(smsCode)) {
            return GraceJSONResult.errorCustom(ResponseStatusEnum.SMS_CODE_ERROR);
        }

        // [3] 查询用户是否存在
        Users users = this.usersService.queryMobileIsExist(mobile);
        if (ObjectUtils.isEmpty(users)) {
            // [3.1] 用户为空,表示没有注册过,users = null,需要注册信息插入数据库
            users = this.usersService.creteUser(mobile);
        }

        // [4] 如果不为空,可以继续下方业务,保存用户信息和会话信息
        String uToken = UUID.randomUUID().toString();
        redis.set(REDIS_USER_TOKEN + ":" + users.getId(), uToken);

        // [5] 用户登录注册成功后,删除redis中的短信验证码
        redis.del(MOBILE_SMSCODE + ":" + mobile);

        // [6] 返回用户信息,Token令牌
        UsersVo usersVo = UsersVo.convertUsersVo(users);
        usersVo.setUserToken(uToken);

        return GraceJSONResult.ok(usersVo);

    }


    @ApiImplicitParam(name = "mobile", value = "手机号", required = true)
    @ApiOperation(value = "短信测试")
    @PostMapping("/getSMSCode")
    public GraceJSONResult sms(@RequestParam(value = "mobile")
                               @ApiParam(name = "mobile", value = "手机号", required = true, format = "11位数") String mobile
            , HttpServletRequest request) {
        try {
            if (StringUtils.isBlank(mobile)) {
                return GraceJSONResult.ok();
            }

            //TODO 获取用户id
            String userIp = IPUtil.getRequestIp(request);

            //TODO  根据用户ip进行限制,限制用户在60之内只能获取一次短信
            redis.setnx60s(MOBILE_SMSCODE + ":" + userIp, userIp);

            String code = (int) ((Math.random() * 9 + 1) * 100000) + "";
            smsUtils.sendSMS(mobile, code);

            log.info("用户手机号 = " + mobile + ", 用户ip = " + userIp + ", 验证码 = " + code);
            //TODO 验证码发送到Redis中
            redis.set(MOBILE_SMSCODE + ":" + mobile, code, 30 * 60);

            return GraceJSONResult.ok("短信发送成功");
        } catch (Exception e) {
            e.printStackTrace();
            return GraceJSONResult.errorMsg("短信发送失败:" + e);
        }
    }


}
